# -*- coding: utf-8 -*-
"""
自建银行卡代理下分
"""
import uuid
import hashlib
import json
import logging
from datetime import datetime

import requests
from django.conf import settings

from common.account.db import account as account_db
from common.stats.account import get_account_aggr
from common.utils import exceptions as err
from common.utils.api import get_city

_LOGGER = logging.getLogger('pay')

MCH_ID = settings.UNIONAGENCY_MCH_ID
API_KEY = settings.UNIONAGENCY_API_KEY
CHARGE_URL = settings.UNIONAGENCY_CHARGE_URL_V2
UNIONAGENCY_PAY_INFO_QUERY_URL = settings.UNIONAGENCY_PAY_INFO_QUERY_URL

PAY_SUCCESS = 1
PAY_FAIL = 2

_PAY_TYPE_MAPPING = {
    1015: 'alipay',
    1016: 'bankcard',
    1017: 'wechat',
}


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += 'key=%s' % key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def fill_union_agent_extra_info(account_id, extra_info):
    account = account_db.get_account(account_id)
    account = account.as_dict()
    account.update(get_account_aggr(account_id))
    # fill union agent extra info
    user_stats = account['user_stats']
    extra_info['user_info']['account_day'] = (datetime.now() - account['created_at']).days
    extra_info['user_info']['total_bet'] = user_stats.get("pay", {}).get("total", 0) + \
                                           user_stats.get("lottery", {}).get("bet_amount", 0) + \
                                           user_stats.get("kfc", {}).get("bet_amount", 0) + \
                                           user_stats.get("fruit", {}).get("bet_amount", 0) + \
                                           user_stats.get("bull", {}).get("bet_amount", 0)
    extra_info['user_info']['total_recharge'] = user_stats.get("recharge", {}).get("total", 0)
    extra_info['user_info']['count_withdraw'] = user_stats.get("withdraw", {}).get("count", 0)
    extra_info['user_info']['count_recharge'] = user_stats.get("recharge", {}).get("count", 0)
    if extra_info['user_info']['total_recharge']:
        extra_info['user_info']['ratio'] = extra_info['user_info']['total_bet'] / extra_info['user_info'][
            'total_recharge']
    else:
        extra_info['user_info']['ratio'] = 0
    return extra_info


def create_charge(pay, pay_amount, sdk_version, extra_info, service, pay_type, account_num, account_username,
                  account_bank):
    total_fee = int(pay_amount)
    fill_union_agent_extra_info(pay.user_id, extra_info)
    client_city = get_city(extra_info['user_info']['device_ip'])
    if not client_city:
        client_city = u'海外'

    try:
        pay_type = int(pay_type)
    except Exception:
        raise err.ParamError('pay_type invalid')

    if pay_type not in _PAY_TYPE_MAPPING:
        raise err.ParamError('pay_type invalid')

    parameter_dict = {
        'service': service,
        'sdk_version': sdk_version,
        'mch_id': MCH_ID,
        'user_id': pay.user_id,
        'out_trade_no': pay.id,
        'body': u'商品',
        'pay_type': _PAY_TYPE_MAPPING.get(pay_type),
        'pay_account_num': account_num,
        'pay_account_username': account_username,
        'pay_account_bank': account_bank,
        'total_fee': total_fee,
        'mch_create_ip': u'127.0.0.1',
        'notify_url': settings.UNIONAGENCY_NOTIFY_URL,
        'context': json.dumps(extra_info, ensure_ascii=False),
        'region': client_city
    }
    parameter_dict['sign'] = generate_sign(parameter_dict, API_KEY)
    res = requests.post(CHARGE_URL, data=parameter_dict, timeout=5).text
    # _LOGGER.info("unionagency data after charge: %s", res)
    res_dict = json.loads(res)
    if res_dict['status'] != 0:
        raise err.ServerError('pay service response %s %s' % (res_dict['status'], res_dict['msg']))

    return_data = res_dict.get('data')
    return return_data


def query_pay_info(order_id):
    parameter_dict = {
        'mch_id': MCH_ID,
        'out_trade_no': order_id,
        'random_num': uuid.uuid4().hex,
    }
    parameter_dict['sign'] = generate_sign(parameter_dict, API_KEY)
    res = requests.post(UNIONAGENCY_PAY_INFO_QUERY_URL, data=parameter_dict, timeout=5).text
    _LOGGER.info(u"query_pay_info: {} {}".format(order_id, res))
    res_dict = json.loads(res)
    return res_dict.get('data')
